import { reqGetCode, reqRegist, reqLogin, reqUserInfo, reqLogout } from "@/api"
const state = {
  code: '',
  token:localStorage.getItem('TOKEN'),
  userInfo:''
}
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state,token){
    state.token = token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },
  CLEAR(state){
    // 清除仓库相关
    state.token =''
    state.userInfo = {}
    // 清除本地存储令牌
    localStorage.removeItem('TOKEN')
  }
}
// 派发action
const actions = {
  //获取验证码
  async getCode({ commit }, phone) {
    let res = await reqGetCode(phone);
    // 后台直接把验证码发到用户手机上，为了节省成本,此处返回验证码
    if (res.data.code === 200) {
      // 返回验证码
      console.log(res.data)
      commit('GETCODE', res.data.data);
      return 'ok';
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户注册
  async userRegist(userInfo){
    // 注册没有返回data,不需要提交mutation
    let res = await reqRegist(userInfo)
    if(res.data.code===200){
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  },
  // 用户登录
  async userLogin({commit},data){
    let res = await reqLogin(data)
    // 服务器下发token--用户唯一标识符(通过token向服务器获取用户信息进行展示)
    if(res.data.code===200){
      commit('USERLOGIN',res.data.data.token)
      // 本地存储
      localStorage.setItem('TOKEN',res.data.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  },
  // 获取用户信息
  async getUserInfo({commit}){
    let res = await reqUserInfo()
      // console.log(res.data)
      if(res.data.code===200){
        commit('GETUSERINFO',res.data.data)
        return 'ok'
      }else{
        return Promise.reject(new Error('faile'))
      }
    
  },
  // 退出登录
  async userLogout({commit}){
    // 通知服务器清除token
    let res = await reqLogout()
    if(res.data.code===200){
      commit('CLEAR')
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  }
}

const getters = {}
export default {
  state,
  mutations,
  actions,
  getters
}